package com.zahb.qadx.ui.fragment;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatButton;
import androidx.appcompat.widget.AppCompatEditText;
import androidx.appcompat.widget.AppCompatTextView;
import androidx.appcompat.widget.LinearLayoutCompat;
import androidx.viewbinding.ViewBinding;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.zahb.qadx.R;
import com.zahb.qadx.base.BaseFragmentV2;
import com.zahb.qadx.databinding.FragmentCreateChoiceExamBinding;
import com.zahb.qadx.model.ExamCategory;
import com.zahb.qadx.model.QuestionBank;
import com.zahb.qadx.model.QuestionInfoBean;
import com.zahb.qadx.ui.activity.CreateChoiceExamActivity2;
import com.zahb.qadx.ui.activity.SelectQuestionBankActivity;
import com.zahb.qadx.ui.activity.ViewExamDetailsActivity;
import com.zahb.qadx.util.CompatHelper;
import com.zahb.qadx.util.DisplayUtil;
import com.zahb.qadx.util.InputMethodUtil;
import com.zahb.qadx.util.JsonUtil;
import com.zahb.qadx.util.SimpleTextWatcher;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

/**
 * Created by Zdw on 2020/11/17 10:14
 */
public class CreateChoiceExamFragment extends BaseFragmentV2 implements View.OnClickListener {

    AppCompatEditText mEtExamName;
    AppCompatTextView mTvExamPaperType;
    AppCompatEditText mEtPassProportion;
    AppCompatTextView mTvDifficultyEasy;
    AppCompatTextView mTvDifficultyMiddle;
    AppCompatTextView mTvDifficultyHard;
    AppCompatTextView mTvSelectRemove;
    AppCompatTextView mTvQuestionBankName;
    LinearLayoutCompat mLayoutQuestionType;
    AppCompatButton mBtnNextStep;

    private OptionsPickerView<ExamCategory> mCategoryPickerView;
    private List<ExamCategory> mExamCategoryList;
    private ExamCategory mCurrentExamCategory;

    private OptionsPickerView<String> mDifficultyPickerView; //条件选择器
    private final String[] mDifficultyEasyArray = new String[]{"简单1", "简单2", "简单3", "简单4", "简单5", "简单6", "简单7", "简单8", "简单9", "简单10"};
    private final String[] mDifficultyMiddleArray = new String[]{"中等1", "中等2", "中等3", "中等4", "中等5", "中等6", "中等7", "中等8", "中等9", "中等10"};
    private final String[] mDifficultyHardArray = new String[]{"困难1", "困难2", "困难3", "困难4", "困难5", "困难6", "困难7", "困难8", "困难9", "困难10"};
    private String mDifficultyInfoJson;

    private QuestionBank mCurrentQuestionBank;
    private List<QuestionInfoBean> mQuestionInfoBeans;

    public static CreateChoiceExamFragment newInstance(String json) {
        Bundle args = new Bundle();
        args.putString("json", json);
        CreateChoiceExamFragment fragment = new CreateChoiceExamFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mExamCategoryList = mArguments.getParcelableArrayList("examCategoryList");
    }

    @org.jetbrains.annotations.Nullable
    @Override
    public ViewBinding initViewBinding(@NotNull LayoutInflater inflater, @org.jetbrains.annotations.Nullable ViewGroup container) {
        FragmentCreateChoiceExamBinding binding = FragmentCreateChoiceExamBinding
                .inflate(inflater, container, false);
        mEtExamName = binding.etExamName;
        mTvExamPaperType = binding.tvExamPaperType;
        mEtPassProportion = binding.etPassProportion;
        mTvDifficultyEasy = binding.tvDifficultyEasy;
        mTvDifficultyMiddle = binding.tvDifficultyMiddle;
        mTvDifficultyHard = binding.tvDifficultyHard;
        mTvSelectRemove = binding.tvSelectRemove;
        mTvQuestionBankName = binding.tvQuestionBankName;
        mLayoutQuestionType = binding.layoutQuestionType;
        mBtnNextStep = binding.btnNextStep;

        binding.tvExamPaperType.setOnClickListener(this);
        binding.tvDifficultyEasy.setOnClickListener(this);
        binding.tvDifficultyMiddle.setOnClickListener(this);
        binding.tvDifficultyHard.setOnClickListener(this);
        binding.tvSelectRemove.setOnClickListener(this);
        binding.btnNextStep.setOnClickListener(this);
        return binding;
    }

    @Override
    protected void initViews(View rootView) {
        mEtPassProportion.setText(new StringBuilder("60"));

        String json = mArguments.getString("json");
        if (!TextUtils.isEmpty(json)) {
            mBtnNextStep.setVisibility(View.VISIBLE);
            mBtnNextStep.setText("查看抽考信息");
            mBtnNextStep.setOnClickListener(v -> {
                if (getActivity() instanceof ViewExamDetailsActivity) {
                    ViewExamDetailsActivity activity = (ViewExamDetailsActivity) getActivity();
                    activity.mViewPager2.setCurrentItem(1, false);
                }
            });

            assert json != null;
            JsonObject jsonObject = JsonParser.parseString(json).getAsJsonObject();
            mEtExamName.setText(jsonObject.get("paperName").getAsString());
            mEtExamName.setEnabled(false);
            mTvExamPaperType.setText(jsonObject.get("cateName").getAsString());
            mTvExamPaperType.setEnabled(false);
            mEtPassProportion.setText(String.valueOf((int) jsonObject.get("passScore").getAsDouble()));
            mEtPassProportion.setEnabled(false);
            String difficultyInfo = jsonObject.get("difficultyInfo").getAsString();
            JsonObject objectDifficultyInfo = JsonParser.parseString(difficultyInfo).getAsJsonObject();
            mTvDifficultyEasy.setText("简单");
            mTvDifficultyEasy.append(objectDifficultyInfo.get("1").getAsString());
            mTvDifficultyEasy.setEnabled(false);
            mTvDifficultyMiddle.setText("中等");
            mTvDifficultyMiddle.append(objectDifficultyInfo.get("2").getAsString());
            mTvDifficultyMiddle.setEnabled(false);
            mTvDifficultyHard.setText("困难");
            mTvDifficultyHard.append(objectDifficultyInfo.get("3").getAsString());
            mTvDifficultyHard.setEnabled(false);
            mTvSelectRemove.setVisibility(View.INVISIBLE);
            if (mLayoutQuestionType.getChildCount() > 1)
                mLayoutQuestionType.removeViews(1, mLayoutQuestionType.getChildCount() - 1);
            JsonArray examPaperRuleList = jsonObject.getAsJsonArray("examPaperRuleList");
            String[] questionTypes = new String[]{"单选", "多选", "判断", "填空", "简答", "案例"};
            for (JsonElement je : examPaperRuleList) {
                JsonObject object = je.getAsJsonObject();
                mTvQuestionBankName.setText(object.get("questionLibName").getAsString());
                int questionType = object.get("questionType").getAsInt();
                // 1：单选，2：多选，3：判断，4：填空，5：简答，6：案例
                JsonArray examPaperRuleInfoList = object.getAsJsonArray("examPaperRuleInfoList");
                JsonObject item = examPaperRuleInfoList.get(0).getAsJsonObject();
                View view = View.inflate(getContext(), R.layout.item_question_type_set, null);
                TextView tv_question_type = view.findViewById(R.id.tv_question_type);
                tv_question_type.setText(questionTypes[questionType - 1]);
                EditText et_question_score = view.findViewById(R.id.et_question_score);
                int score = item.get("score").getAsInt();
                et_question_score.setText(String.valueOf(score));
                et_question_score.setGravity(Gravity.CENTER);
                et_question_score.setEnabled(false);
                EditText et_question_count = view.findViewById(R.id.et_question_count);
                int questionCount = item.get("questionCount").getAsInt();
                et_question_count.setText(String.valueOf(questionCount));
                et_question_count.setGravity(Gravity.CENTER);
                et_question_count.setEnabled(false);
                TextView tv_question_count = view.findViewById(R.id.tv_question_count);
                int questionTotal = item.get("questionTotal").getAsInt();
                tv_question_count.setText(new StringBuilder("/").append(questionTotal));
                TextView tv_question_sum = view.findViewById(R.id.tv_question_sum);
                tv_question_sum.setText(new StringBuilder(questionTypes[questionType - 1]).append(score * questionCount).append("分"));
                mLayoutQuestionType.addView(view);
                LinearLayoutCompat.LayoutParams lp = (LinearLayoutCompat.LayoutParams) view.getLayoutParams();
                lp.height = DisplayUtil.dip2px(34f);
                view.setLayoutParams(lp);
            }
        }
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.tv_exam_paper_type) {
            // 试卷分类
            InputMethodUtil.hideInputMethod(getActivity());
            showCategoryPickerView();
        } else if (v.getId() == R.id.tv_difficulty_easy
                || v.getId() == R.id.tv_difficulty_middle
                || v.getId() == R.id.tv_difficulty_hard) {
            // 难度控制
            InputMethodUtil.hideInputMethod(getActivity());
            showDifficultyPickerView();
        } else if (v.getId() == R.id.tv_select_remove) {
            // 选择题库
            if (CompatHelper.isEmpty(mDifficultyInfoJson)) {
                showBindToast("请进行难度控制");
                return;
            }
            Intent intent = new Intent(getContext(), SelectQuestionBankActivity.class);
            intent.putExtra("difficultyInfo", mDifficultyInfoJson);
            if (mCurrentQuestionBank != null)
                intent.putExtra("id", mCurrentQuestionBank.getId());
            startActivityForResult(intent, 0x101);
        } else if (v.getId() == R.id.btn_next_step) {
            // 下一步
            if (CompatHelper.isEmpty(mEtExamName)) {
                showBindToast("请填写试卷名称");
                return;
            }
            if (mCurrentExamCategory == null) {
                showBindToast("请选择试卷分类");
                return;
            }
            if (CompatHelper.isEmpty(mEtPassProportion)) {
                showBindToast("请填写及格比例");
                return;
            }
            int passProportion = Integer.parseInt(CompatHelper.getString(mEtPassProportion));
            if (passProportion >= 100) {
                showBindToast("及格比例不能大于100");
                return;
            }
            if (CompatHelper.isEmpty(mDifficultyInfoJson)) {
                showBindToast("请进行难度设置");
                return;
            }
            if (mCurrentQuestionBank == null) {
                showBindToast("请选择题库");
                return;
            }
            int totalScore = 0;
            for (int i = 0; i < mQuestionInfoBeans.size(); i++) {
                totalScore += mQuestionInfoBeans.get(i).getTotalScore();
            }
            if (totalScore <= 0) {
                showBindToast("请设置题型");
                return;
            }
            Map<String, Object> params = wrapParams();
            String json = JsonUtil.getGson().toJson(params);
            Log.e("zdw", "create pager json: " + json);
            Intent intent = new Intent(getContext(), CreateChoiceExamActivity2.class);
            intent.putExtra("json", json);
            startActivity(intent);
        }
    }

    private void showCategoryPickerView() {
        if (mCategoryPickerView == null) {
            List<List<ExamCategory>> examCategories = new ArrayList<>();
            for (int i = 0; i < mExamCategoryList.size(); i++) {
                List<ExamCategory> childList = new ArrayList<>();
                childList.add(mExamCategoryList.get(i));
                if (mExamCategoryList.get(i).getChildList() != null)
                    childList.addAll(mExamCategoryList.get(i).getChildList());
                examCategories.add(childList);
            }
            mCategoryPickerView = new OptionsPickerBuilder(getContext(), (options1, options2, options3, v) -> {
                mTvExamPaperType.setText(examCategories.get(options1).get(options2).getName());
                mCurrentExamCategory = examCategories.get(options1).get(options2);
            }).setTitleText(getString(R.string.exam_paper_type)).build();
            mCategoryPickerView.setPicker(mExamCategoryList, examCategories);
        }
        mCategoryPickerView.show();
    }

    private final Map<String, Object> params = new TreeMap<>();

    private void showDifficultyPickerView() {
        if (mDifficultyPickerView == null) {
            mDifficultyPickerView = new OptionsPickerBuilder(getContext(), (options1, options2, options3, v) -> {
                mTvDifficultyEasy.setText(mDifficultyEasyArray[options1]);
                mTvDifficultyMiddle.setText(mDifficultyMiddleArray[options2]);
                mTvDifficultyHard.setText(mDifficultyHardArray[options3]);
                params.clear();
                params.put("1", options1 + 1);
                params.put("2", options2 + 1);
                params.put("3", options3 + 1);
                mDifficultyInfoJson = JsonUtil.getGson().toJson(params);
            }).setTitleText(getString(R.string.difficulty_select)).setSelectOptions(2, 3, 2).build();
            mDifficultyPickerView.setNPicker(
                    Arrays.asList(mDifficultyEasyArray),
                    Arrays.asList(mDifficultyMiddleArray),
                    Arrays.asList(mDifficultyHardArray));
        }
        mDifficultyPickerView.show();
    }

    private Map<String, Object> wrapParams() {
        Map<String, Object> params = new TreeMap<>();
        params.put("paperName", CompatHelper.getString(mEtExamName));
        params.put("paperType", 1);
        params.put("paperMode", 0);
        params.put("cateId", mCurrentExamCategory.getId());
        params.put("cateName", mCurrentExamCategory.getName());
        params.put("passScore", Integer.parseInt(CompatHelper.getString(mEtPassProportion)));
        params.put("difficultyInfo", mDifficultyInfoJson);
        List<Map<String, Object>> examPaperRuleList = new ArrayList<>();
        int totalScore = 0;
        int questionCount = 0;
        for (int i = 0; i < mQuestionInfoBeans.size(); i++) {
            QuestionInfoBean bean = mQuestionInfoBeans.get(i);
            totalScore += bean.getTotalScore();
            questionCount += bean.getCount();
            Map<String, Object> map = new TreeMap<>();
            map.put("questionType", bean.getType());
            map.put("questionLibId", mCurrentQuestionBank.getId());
            map.put("questionLibName", mCurrentQuestionBank.getName());
            map.put("opreationType", 1);
            map.put("sort", i);
            List<Map<String, Object>> examPaperRuleInfoList = new ArrayList<>();
            Map<String, Object> map1 = new TreeMap<>();
            map1.put("difficultyLevel", 4);
            map1.put("score", bean.getScore());
            map1.put("questionCount", bean.getCount());
            map1.put("questionTotal", (int) bean.getComprehensive());
            map1.put("opreationType", 1);
            examPaperRuleInfoList.add(map1);
            map.put("examPaperRuleInfoList", examPaperRuleInfoList);
            examPaperRuleList.add(map);
        }
        params.put("examPaperRuleList", examPaperRuleList);
        params.put("totalScore", totalScore);
        params.put("questionCount", questionCount);
        params.put("opreationType", 1);
        params.put("isPublish", 1);
        return params;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0x101 && resultCode == Activity.RESULT_OK && data != null) {
            Bundle bundle = data.getExtras() != null ? data.getExtras() : new Bundle();
            QuestionBank questionBank = bundle.getParcelable("questionBank");
            if (questionBank != null) {
                mCurrentQuestionBank = questionBank;
                mTvQuestionBankName.setText(mCurrentQuestionBank.getName());
            }

            List<QuestionInfoBean> questionInfoBeans = bundle.getParcelableArrayList("questionInfoBeans");
            if (questionInfoBeans != null) {
                mQuestionInfoBeans = questionInfoBeans;

                if (mLayoutQuestionType.getChildCount() > 1)
                    mLayoutQuestionType.removeViews(1, mLayoutQuestionType.getChildCount() - 1);

                for (int i = 0; i < questionInfoBeans.size(); i++) {
                    QuestionInfoBean questionInfoBean = questionInfoBeans.get(i);
                    View view = View.inflate(getContext(), R.layout.item_question_type_set, null);
                    TextView tv_question_type = view.findViewById(R.id.tv_question_type);
                    tv_question_type.setText(questionInfoBean.getTypeName());
                    EditText et_question_score = view.findViewById(R.id.et_question_score);
                    et_question_score.setGravity(Gravity.CENTER);
                    EditText et_question_count = view.findViewById(R.id.et_question_count);
                    et_question_count.setGravity(Gravity.CENTER);
                    TextView tv_question_count = view.findViewById(R.id.tv_question_count);
                    tv_question_count.setText(new StringBuilder("/").append((int) questionInfoBean.getComprehensive()));
                    TextView tv_question_sum = view.findViewById(R.id.tv_question_sum);
                    tv_question_sum.setText(new StringBuilder(questionInfoBean.getTypeName()).append(0).append("分"));
                    wrapQuestionTypeSet(questionInfoBean, et_question_score, et_question_count, tv_question_sum);
                    mLayoutQuestionType.addView(view);
                    LinearLayoutCompat.LayoutParams lp = (LinearLayoutCompat.LayoutParams) view.getLayoutParams();
                    lp.height = DisplayUtil.dip2px(34f);
                    view.setLayoutParams(lp);
                }
            }
        }
    }

    private void wrapQuestionTypeSet(QuestionInfoBean bean, EditText et_question_score, EditText et_question_count, TextView tv_question_sum) {
        SimpleTextWatcher simpleTextWatcher = new SimpleTextWatcher() {
            @Override
            public void afterTextChanged(Editable s) {
                if (!CompatHelper.isEmpty(et_question_count)) {
                    int count = Integer.parseInt(CompatHelper.getString(et_question_count));
                    int maxCount = (int) bean.getComprehensive();
                    if (count > maxCount) {
                        showBindToast("数量最大为" + maxCount);
                        et_question_count.setText(String.valueOf(maxCount));
                        et_question_count.setSelection(String.valueOf(maxCount).length());
                    }
                }
                if (!CompatHelper.isEmpty(et_question_score) && !CompatHelper.isEmpty(et_question_count)) {
                    int score = Integer.parseInt(CompatHelper.getString(et_question_score));
                    int count = Integer.parseInt(CompatHelper.getString(et_question_count));
                    tv_question_sum.setText(new StringBuilder(bean.getTypeName()).append(score * count).append("分"));
                    bean.setScore(score);
                    bean.setCount(count);
                    bean.setTotalScore(score * count);
                }
            }
        };
        et_question_score.addTextChangedListener(simpleTextWatcher);
        et_question_count.addTextChangedListener(simpleTextWatcher);
    }
}
